package com.smp.bitmapgridtest;

import java.io.File;
import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class BitmapWorkerTask extends AsyncTask<Void, Void, Bitmap> {
	
	private final WeakReference<ImageView> mTargetImageViewRef;
	private File mTargetFile;
	private OnBitmapWorkerListener mListener;
	
	public BitmapWorkerTask(ImageView aTargetImageView, File aTargetFile) {
		mTargetImageViewRef = new WeakReference<ImageView>(aTargetImageView);
		mTargetFile = aTargetFile;
	}
	
	public File getTargetFile() {
		return mTargetFile;
	}
	
	@Override
	protected Bitmap doInBackground(Void... aParams) {
		return decodeSampledBitmapFromFile(mTargetFile, 100, 100);
	}
	@Override
	protected void onPostExecute(Bitmap aResult) {
		if(isCancelled()) {
			aResult = null;
		}
		
		if(mTargetImageViewRef != null && aResult != null) {
			final ImageView targetView = mTargetImageViewRef.get();
			
			final BitmapWorkerTask bitmapWorkerTask = BitmapWorkerHelper.getBitmapWorkerTask(targetView);
			
			if(this == bitmapWorkerTask && targetView != null) {
				targetView.setImageBitmap(aResult);
				if(mListener != null) {
					mListener.onBitmapLoaded(mTargetFile.getAbsolutePath(), aResult);
				}
			}
		}
	}
	
	private static Bitmap decodeSampledBitmapFromFile(File aFile, int aReqWidth, int aReqHeight) {
		
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(aFile.getAbsolutePath(), options);
		
		options.inSampleSize = calculateSampleSize(options, aReqWidth, aReqHeight);
		
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(aFile.getAbsolutePath(), options);
		
	}
	
	private static int calculateSampleSize(BitmapFactory.Options aOptions, int aReqWidth, int aReqHeight) {
		
		final int width = aOptions.outWidth;
		final int height = aOptions.outHeight;
		int inSampleSize = 1;
		
		if(width > aReqWidth || height > aReqHeight) {
			
			final int widthRatio = Math.round((float) width / (float) aReqWidth);
			final int heightRatio = Math.round((float) height / (float) aReqHeight);
			
			inSampleSize = widthRatio < heightRatio ? widthRatio : heightRatio;
			
		}
		
		return inSampleSize;
	}
	
	public void setOnBitmapWorkerListener(OnBitmapWorkerListener aListener) {
		mListener = aListener;
	}
	
	public interface OnBitmapWorkerListener {
		public void onBitmapLoaded(String aFilePath, Bitmap aBitmap);
	}
}
